/**
 * 编辑邮件配置页面
 */
import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import {
  Card,
  Form,
  Input,
  InputNumber,
  Select,
  Button,
  Space,
  message,
  Row,
  Col,
  Alert,
  Divider,
  Spin,
} from 'antd';
import { ArrowLeftOutlined, ApiOutlined } from '@ant-design/icons';
import { history, useParams } from '@umijs/max';
import {
  getEmailConfig,
  updateEmailConfig,
  testEmailConfig,
  type EmailConfigUpdate,
  type EmailConfigTest,
  EncryptionType,
} from '@/services/emailConfig';

const { Option } = Select;

const EditEmailConfig: React.FC = () => {
  const params = useParams();
  const configId = parseInt(params.id as string);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [testLoading, setTestLoading] = useState(false);
  const [pageLoading, setPageLoading] = useState(true);
  const [testResult, setTestResult] = useState<any>(null);

  // 获取邮件配置详情
  const fetchEmailConfig = async () => {
    try {
      const config = await getEmailConfig(configId);
      form.setFieldsValue({
        name: config.name,
        smtp_host: config.smtp_host,
        smtp_port: config.smtp_port,
        username: config.username,
        from_email: config.from_email,
        from_name: config.from_name,
        encryption: config.encryption,
        timeout: config.timeout,
        description: config.description,
      });
    } catch (error: any) {
      message.error(error.message || '获取配置详情失败');
      history.push('/email-configs');
    } finally {
      setPageLoading(false);
    }
  };

  useEffect(() => {
    if (configId) {
      fetchEmailConfig();
    }
  }, [configId]);

  // 处理表单提交
  const handleSubmit = async (values: EmailConfigUpdate) => {
    setLoading(true);
    try {
      await updateEmailConfig(configId, values);
      message.success('邮件配置更新成功');
      history.push('/email-configs');
    } catch (error: any) {
      message.error(error.message || '更新失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理连接测试
  const handleTestConnection = async () => {
    try {
      const values = await form.validateFields([
        'smtp_host',
        'smtp_port',
        'username',
        'password',
        'from_email',
        'encryption',
        'timeout',
      ]);

      setTestLoading(true);
      setTestResult(null);

      const testData: EmailConfigTest = {
        smtp_host: values.smtp_host,
        smtp_port: values.smtp_port,
        username: values.username,
        password: values.password || '***', // 如果密码为空，使用占位符
        from_email: values.from_email,
        encryption: values.encryption,
        timeout: values.timeout,
      };

      const result = await testEmailConfig(testData);
      setTestResult(result);

      if (result.success) {
        message.success(result.message);
      } else {
        message.error(result.message);
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.warning('请先填写完整的SMTP配置信息');
      } else {
        message.error(error.message || '连接测试失败');
      }
    } finally {
      setTestLoading(false);
    }
  };

  if (pageLoading) {
    return (
      <PageContainer>
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
          </div>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      header={{
        title: '编辑邮件配置',
        breadcrumb: {},
      }}
      extra={[
        <Button
          key="back"
          icon={<ArrowLeftOutlined />}
          onClick={() => history.push('/email-configs')}
        >
          返回列表
        </Button>,
      ]}
    >
      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="name"
                label="配置名称"
                rules={[
                  { required: true, message: '请输入配置名称' },
                  { min: 2, message: '配置名称至少需要2个字符' },
                ]}
              >
                <Input placeholder="请输入配置名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="description" label="配置描述">
                <Input placeholder="请输入配置描述（可选）" />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">SMTP服务器配置</Divider>

          <Row gutter={24}>
            <Col span={16}>
              <Form.Item
                name="smtp_host"
                label="SMTP服务器地址"
                rules={[{ required: true, message: '请输入SMTP服务器地址' }]}
              >
                <Input placeholder="例如：smtp.qq.com" />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                name="smtp_port"
                label="端口"
                rules={[
                  { required: true, message: '请输入端口号' },
                  { type: 'number', min: 1, max: 65535, message: '端口号必须在1-65535之间' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="587"
                  min={1}
                  max={65535}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入SMTP用户名" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="password"
                label="密码"
                extra="留空则保持原密码不变"
              >
                <Input.Password placeholder="请输入新密码（留空保持不变）" />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="encryption"
                label="加密方式"
                rules={[{ required: true, message: '请选择加密方式' }]}
              >
                <Select placeholder="请选择加密方式">
                  <Option value={EncryptionType.NONE}>无加密</Option>
                  <Option value={EncryptionType.SSL}>SSL</Option>
                  <Option value={EncryptionType.STARTTLS}>STARTTLS</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="timeout"
                label="连接超时时间（秒）"
                rules={[
                  { required: true, message: '请输入超时时间' },
                  { type: 'number', min: 5, max: 300, message: '超时时间必须在5-300秒之间' },
                ]}
              >
                <InputNumber
                  style={{ width: '100%' }}
                  placeholder="30"
                  min={5}
                  max={300}
                />
              </Form.Item>
            </Col>
          </Row>

          <Divider orientation="left">发件人信息</Divider>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="from_email"
                label="发件人邮箱"
                rules={[
                  { required: true, message: '请输入发件人邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
              >
                <Input placeholder="请输入发件人邮箱地址" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item name="from_name" label="发件人姓名">
                <Input placeholder="请输入发件人姓名（可选）" />
              </Form.Item>
            </Col>
          </Row>

          {/* 连接测试结果 */}
          {testResult && (
            <Alert
              message={testResult.success ? '连接测试成功' : '连接测试失败'}
              description={testResult.message}
              type={testResult.success ? 'success' : 'error'}
              showIcon
              style={{ marginBottom: 16 }}
            />
          )}

          <Form.Item>
            <Space>
              <Button
                type="default"
                icon={<ApiOutlined />}
                onClick={handleTestConnection}
                loading={testLoading}
              >
                测试连接
              </Button>
              <Button type="primary" htmlType="submit" loading={loading}>
                更新配置
              </Button>
              <Button onClick={() => history.push('/email-configs')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </PageContainer>
  );
};

export default EditEmailConfig;
